<?php
namespace addons\sign\controllers;
use addons\member\models\Member;
use addons\sign\libs\Golds;
use addons\sign\libs\SignIn;
use controllers\AdminApi;

/**
 * @auth    签到记录
 * @author Colin <xiongxinsheng@yikaosheng.com>
 * @date 2021-05-12 下午6:00
 * @package addons\sign\controllers
 */
class Index extends AdminApi{
	/**
	 * @var Golds $gold
	 */
	protected $gold = '';
	/**
	 * @var SignIn $model
	 */
	protected $model = '';
	/**
	 * 初始化
	 */
	public function onStepUp(){
		$this->gold = new Golds();
		$this->model = new SignIn(0 , $this->gold->getGoldCount());
	}

	/**
	 * @auth 签到记录
	 * @param string $title
	 * @return array
	 */
	public function index($title = '') {
		$redis = getRedis();
		// 获取数据
		$stateKey = 'shopUserSignIn:state:';
		$dateKey = 'shopUserSignIn:lastDate:';
		$keys = $redis->keys($stateKey . '*');
		$end = values('get.limit' , 10);
		$page = values('get.page' , 1);
		if ($page == 1 || $page < 1){
			$start = 0;
		}else{
			$start = ($page - 1) * $end;
		}
		$memberModel = new Member();
		$userIds = $memberModel->getFind(['nickname' => $title] , 'id');
		if (count($userIds) > 0){
			$keys = [];
			foreach ($userIds as $key => $val){
				$redis->exists($stateKey . $val['id']) && array_push($keys , $stateKey . $val['id']);
			}
		}
		$allDay = $this->gold->getGoldCount();
		$list = [];
		if (count($keys) > 0){
			$splice = array_splice($keys , $start , $end);
			$currentDate = date('Ymd');
			foreach ($splice as $key => $val){
				$explode = explode(':' , $val);
				$member_id = array_pop($explode);
				if ($member_id){
					$memberFind = $memberModel->getFind(['id' => $member_id] , 'id,nickname');
					// 当前第几天
					if (!$memberFind){
						continue;
					}
					$dayKey = $dateKey . $member_id;
					$memberFind['member_id'] = $member_id;
					$memberFind['day'] = $redis->bitCount($val) . '/' . $allDay;
					$memberFind['second'] = $redis->ttl($val) . '-' . $redis->ttl($dayKey);
					$memberFind['last_date'] = $redis->get($dayKey);
					// 今天是否签到
					$day = $this->model->getManyDay($memberFind['last_date'] , $currentDate , $allDay);
					$memberFind['today'] = $this->model->redisBitField($val , $day);
					$memberFind['today'] = $memberFind['today'] ? '<span style="color:green">是</span>' : '<span style="color:red">否</span>';
					array_push($list , $memberFind);
				}
			}
		}
		return self::returnJson($list);
	}

	public function delete($id = '') {
		if (is_numeric($id)){
			$model = new SignIn($id , $this->gold->getGoldCount());
			$res = $model->resetUserSign();
			if ($res){
				return success('删除成功');
			}
			return error('删除失败');
		}
		return error('删除失败');
	}

	/**
	 * 设置弹窗标题
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setPageTitle() {
		return '签到记录';
	}

	/**
	 * 设置面包屑
	 * @return array
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setCrumbs() {
		return ['会员管理' , '签到列表'];
	}
}